package com.gitee.form_token.security;

import com.gitee.form_token.entity.MyUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("myValid")
public class AuthorityValidator {
    public boolean has(String authority) {

        // 获取当前认证用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        try {
            if (authentication.isAuthenticated()) {
                MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();

                // 获取用户权限信息
                List<String> authorityList = userDetails.getAuthorityList();
                System.out.println("authority===" + authority);
                System.out.println("authorityList===" + authorityList);

                return authorityList.contains(authority);
            }
        } catch (AuthenticationException ex) {
            System.out.println("myValid ->" + ex.getMessage());
        }

        return false;
    }
}
